//
//  ViewController.swift
//  5.2.Detecting and Reacting to Collisions Between UI Components
//
//  Created by joker on 15/7/31.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UICollisionBehaviorDelegate {

    let bottomBoundary = "bottomBoundary"

    var squareViews = [AnyObject]()
    var animator: UIDynamicAnimator?
    
    func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying, atPoint p: CGPoint) {
        if identifier as? String == bottomBoundary {
            UIView.animateWithDuration(1, animations: {
                let view = item as! UIView
                view.backgroundColor = UIColor.redColor()
                view.alpha = 0
                view.transform = CGAffineTransformMakeScale(2, 2)
                },completion: { (finished: Bool) in
                    let view = item as! UIView
                    behavior.removeItem(item)
                    view.removeFromSuperview()
            })
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        let colors = [UIColor.redColor(), UIColor.greenColor()]
        
        var currentCenterPoint = CGPoint(x: view.center.x, y: 0)
        
        let eachViewSize = CGSize(width: 50, height: 50)
        for counter in 0 ..< 2 {
            let newView = UIView(frame: CGRect(x: 0, y: 0, width: eachViewSize.width, height: eachViewSize.height))
            newView.backgroundColor = colors[counter]
            newView.center = currentCenterPoint
            currentCenterPoint.y += eachViewSize.height + 10
            squareViews.append(newView)
            view.addSubview(newView)
        }
        
        animator = UIDynamicAnimator(referenceView: self.view)
        
        let gravity = UIGravityBehavior(items: squareViews)
        animator!.addBehavior(gravity)
        
        let collision = UICollisionBehavior(items: squareViews)

        let fromPoint = CGPoint(x: 0, y: view.bounds.size.height - 100)
        let toPoint = CGPoint(x: view.bounds.size.width, y: view.bounds.size.height - 100)
        collision.addBoundaryWithIdentifier(bottomBoundary, fromPoint: fromPoint, toPoint:toPoint)
        
        collision.collisionDelegate = self
        
        collision.collisionMode = .Everything
        
        animator!.addBehavior(collision)
    }
}

